<template>
  <!-- DiversionShare -->
  <div v-loading="isLoading">
    <div class="title-container">
      <el-icon><Notebook /></el-icon>
      <span style="padding-left: 8px">返航/备降记录</span>
    </div>
    <div class="cmdbar-container">
      <el-form inline size="small">
        <el-form-item label="显示范围">
          <el-radio-group v-model="queryConditions.rangeType">
            <el-radio label="实时(2h内)" value="current"></el-radio>
            <el-radio label="自定义时段" value="custom"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-show="queryConditions.rangeType == 'custom'">
          <div class="cmdbar-item-container">
            <el-date-picker
              v-model="queryConditions.startDate"
              type="date"
              value-format="YYYY-MM-DD"
              format="YYYY-MM-DD"
              :clearable="false"
              style="width: 120px; margin-right: 8px"
            />
            <el-time-picker
              v-model="queryConditions.startTime"
              value-format="HH:mm:ss"
              format="HH:mm:ss"
              :clearable="false"
              style="width: 120px; margin-right: 8px"
            />
            <el-icon style="margin-right: 8px">
              <svg
                viewBox="0 0 20 20"
                version="1.1"
                xmlns="http://www.w3.org/2000/svg"
              >
                <g stroke-width="1" fill-rule="evenodd">
                  <g fill="currentColor">
                    <path
                      d="M11.2654,3.20511 C10.9644,2.92049 10.4897,2.93371 10.2051,3.23464 C9.92049,3.53558 9.93371,4.01027 10.2346,4.29489 L15.4737,9.25 L2.75,9.25 C2.33579,9.25 2,9.58579 2,10.0000012 C2,10.4142 2.33579,10.75 2.75,10.75 L15.476,10.75 L10.2346,15.7073 C9.93371,15.9919 9.92049,16.4666 10.2051,16.7675 C10.4897,17.0684 10.9644,17.0817 11.2654,16.797 L17.6826,10.7276 C17.8489,10.5703 17.9489,10.3702 17.9826,10.1614 C17.994,10.1094 18,10.0554 18,10.0000012 C18,9.94241 17.9935,9.88633 17.9812,9.83246 C17.9462,9.62667 17.8467,9.42976 17.6826,9.27455 L11.2654,3.20511 Z"
                    />
                  </g>
                </g>
              </svg>
            </el-icon>
            <el-date-picker
              v-model="queryConditions.endDate"
              type="date"
              value-format="YYYY-MM-DD"
              format="YYYY-MM-DD"
              :clearable="false"
              style="width: 120px; margin-right: 8px"
            />
            <el-time-picker
              v-model="queryConditions.endTime"
              value-format="HH:mm:ss"
              format="HH:mm:ss"
              :clearable="false"
              style="width: 120px; margin-right: 8px"
            />
            <el-button
              type="primary"
              style="margin-left: 16px"
              @click="handleCustomQuery"
            >
              <el-icon>
                <search />
              </el-icon>
              <span>检索</span>
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-container">
      <el-table
        :data="tableData"
        size="small"
        stripe
        height="calc(100vh - 210px)"
        style="max-width: 100%"
      >
        <el-table-column label="日期" prop="eventDate" min-width="100" />
        <el-table-column label="航班号" prop="flightNumber" min-width="100" />
        <el-table-column
          label="起飞机场"
          prop="departureAirport"
          min-width="90"
        />
        <el-table-column
          label="目落地机场"
          prop="destinationAirport"
          min-width="90"
        />

        <el-table-column label="机组意图" min-width="90">
          <template #default="scope">
            <el-text v-if="scope.row.crewIntention == 'RTN'" type="warning">
              <span style="margin-left: 8px">返航</span>
            </el-text>
            <el-text v-else>
              <span style="margin-left: 8px">备降</span>
            </el-text>
          </template>
        </el-table-column>

        <el-table-column
          label="备降机场"
          prop="diversionAirport"
          min-width="100"
        />
        <el-table-column label="录入时间" prop="origionTime" min-width="180" />
        <el-table-column label="原因" prop="eventReason" min-width="90" />

        <el-table-column label="紧急" min-width="80">
          <template #default="scope">
            <el-text v-if="scope.row.isEmergency" type="danger">
              <el-icon><WarnTriangleFilled /></el-icon>
            </el-text>
          </template>
        </el-table-column>

        <el-table-column label="机型" prop="aircraftType" min-width="90" />
        <el-table-column
          label="计划备降场"
          prop="isPlannedDiversionAirport"
          min-width="100"
        />

        <el-table-column label="计划室" min-width="100">
          <template #default="scope">
            <el-text
              v-if="scope.row.reportPlan == 0"
              type="danger"
              class="vertical-align-center"
            >
              <el-icon><WarningFilled /></el-icon>
              <span style="margin-left: 8px">未通报</span>
            </el-text>
            <el-text
              v-else-if="scope.row.reportPlan == 1"
              type="success"
              class="vertical-align-center"
            >
              <el-icon><SuccessFilled /></el-icon>
              <span style="margin-left: 8px">已通报</span>
            </el-text>
            <el-text
              v-else-if="scope.row.reportPlan == 2"
              type="info"
              class="vertical-align-center"
            >
              <el-icon><RemoveFilled /></el-icon>
              <span style="margin-left: 8px">已忽略</span>
            </el-text>
          </template>
        </el-table-column>

        <el-table-column label="军民航" min-width="100">
          <template #default="scope">
            <el-text
              v-if="scope.row.reportFlow == 0"
              type="danger"
              class="vertical-align-center"
            >
              <el-icon><WarningFilled /></el-icon>
              <span style="margin-left: 8px">未通报</span>
            </el-text>
            <el-text
              v-else-if="scope.row.reportFlow == 1"
              type="success"
              class="vertical-align-center"
            >
              <el-icon><SuccessFilled /></el-icon>
              <span style="margin-left: 8px">已通报</span>
            </el-text>
            <el-text
              v-else-if="scope.row.reportFlow == 2"
              type="info"
              class="vertical-align-center"
            >
              <el-icon><RemoveFilled /></el-icon>
              <span style="margin-left: 8px">已忽略</span>
            </el-text>
          </template>
        </el-table-column>

        <el-table-column type="expand">
          <template #default="props">
            <div class="row-opreator-container">
              <el-descriptions :column="4" size="small" border>
                <el-descriptions-item label="初始席位IP地址">{{
                  props.row.origionSeatIP
                }}</el-descriptions-item>
                <el-descriptions-item label="初始席位名称">{{
                  props.row.origionSeatName
                }}</el-descriptions-item>
                <el-descriptions-item label="初始席位管制员">{{
                  props.row.origionSeatUser
                }}</el-descriptions-item>
                <el-descriptions-item label="初始席位录入时间">{{
                  props.row.origionTime
                }}</el-descriptions-item>
                <!-- 报告计划室 -->
                <el-descriptions-item
                  v-if="props.row.reportPlan"
                  label="报告计划室席位IP"
                  >{{ props.row.reportPlanSeatIP }}</el-descriptions-item
                >
                <el-descriptions-item
                  v-if="props.row.reportPlan"
                  label="报告计划室席位名称"
                  >{{ props.row.reportPlanSeatName }}</el-descriptions-item
                >
                <el-descriptions-item
                  v-if="props.row.reportPlan"
                  label="报告计划室席位管制员"
                  >{{ props.row.reportPlanSeatUser }}</el-descriptions-item
                >
                <el-descriptions-item
                  v-if="props.row.reportPlan"
                  label="报告计划室时间"
                  >{{ props.row.reportPlanTime }}</el-descriptions-item
                >
                <!-- 报告军民航 -->
                <el-descriptions-item
                  v-if="props.row.reportFlow"
                  label="报告军民航席位IP"
                  >{{ props.row.reportFlowSeatIP }}</el-descriptions-item
                >
                <el-descriptions-item
                  v-if="props.row.reportFlow"
                  label="报告军民航席位名称"
                  >{{ props.row.reportFlowSeatName }}</el-descriptions-item
                >
                <el-descriptions-item
                  v-if="props.row.reportFlow"
                  label="报告军民航席位管制员"
                  >{{ props.row.reportFlowSeatUser }}</el-descriptions-item
                >
                <el-descriptions-item
                  v-if="props.row.reportFlow"
                  label="报告军民航时间"
                  >{{ props.row.reportFlowTime }}</el-descriptions-item
                >
                <!-- 操作 -->
                >
                <el-descriptions-item
                  :span="4"
                  :label="`将 ${props.row.flightNumber} 标记为`"
                >
                  <el-button
                    size="small"
                    text
                    @click="updateItem(props.row, 'reportPlan', 0)"
                    :type="props.row.reportPlan == 0 ? 'warning' : 'info'"
                  >
                    <span>未通报计划室</span>
                  </el-button>

                  <el-button
                    size="small"
                    text
                    @click="updateItem(props.row, 'reportPlan', 1)"
                    :type="props.row.reportPlan == 1 ? 'warning' : 'info'"
                  >
                    <span>已通报计划室</span>
                  </el-button>
                  <el-button
                    size="small"
                    text
                    @click="updateItem(props.row, 'reportPlan', 2)"
                    :type="props.row.reportPlan == 2 ? 'warning' : 'info'"
                  >
                    <span>忽略计划室</span>
                  </el-button>
                  <el-divider direction="vertical" />
                  <el-button
                    size="small"
                    text
                    @click="updateItem(props.row, 'reportFlow', 0)"
                    :type="props.row.reportFlow == 0 ? 'warning' : 'info'"
                  >
                    <span>未通报军民航</span>
                  </el-button>
                  <el-button
                    size="small"
                    text
                    @click="updateItem(props.row, 'reportFlow', 1)"
                    :type="props.row.reportFlow == 1 ? 'warning' : 'info'"
                  >
                    <span>已通报军民航</span>
                  </el-button>
                  <el-button
                    size="small"
                    text
                    @click="updateItem(props.row, 'reportFlow', 2)"
                    :type="props.row.reportFlow == 2 ? 'warning' : 'info'"
                  >
                    <span>忽略军民航</span>
                  </el-button>
                  <!-- 删除 -->
                  <el-divider direction="vertical" />
                  <el-popconfirm
                    :title="`确认要删除 ${props.row.flightNumber} 的记录吗？`"
                    confirm-button-text="删除"
                    cancel-button-text="取消"
                    confirm-button-type="danger"
                    width="260px"
                    @confirm="updateItem(props.row, 'setDisposed', 1)"
                  >
                    <template #reference>
                      <el-button size="small" text type="danger">
                        <el-icon><Delete /></el-icon>
                        <span>删除该记录</span>
                      </el-button>
                    </template>
                  </el-popconfirm>
                </el-descriptions-item>
              </el-descriptions>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, nextTick, onMounted, onUnmounted } from "vue";
// import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
// import axios from "axios";
import dayjs from "dayjs";
import useSeatStore from "@/store/seat.js";
import useJournalStore from "@/store/journal.js";
import handleSave from "./handleSave.js";
import handleQuery from "./handleQuery.js";

const seatStore = useSeatStore();
const journalStore = useJournalStore();

const queryConditions = ref({
  rangeType: "current",
  startDate: dayjs().subtract(24, "hour").format("YYYY-MM-DD"),
  startTime: dayjs().subtract(24, "hour").format("HH:mm:ss"),
  endDate: dayjs().format("YYYY-MM-DD"),
  endTime: dayjs().format("HH:mm:ss"),
  timeRange: function () {
    if (this.rangeType == "custom") {
      return {
        from: this.startDate + " " + this.startTime,
        to: this.endDate + " " + this.endTime,
      };
    } else {
      return {
        from: dayjs().subtract(2, "hour").format("YYYY-MM-DD HH:mm:ss"),
        to: dayjs().format("YYYY-MM-DD HH:mm:ss"),
      };
    }
  },
  selectedAirports: [],
  airportRange: function () {
    return this.selectedAirports.length ? this.selectedAirports : null;
  },
  selectedIntentions: [],
  intentionRange: function () {
    return this.selectedIntentions.length ? this.selectedIntentions : null;
  },
  selectedPlanStatus: [],
  planStatusRange: function () {
    return this.selectedPlanStatus.length ? this.selectedPlanStatus : null;
  },
  selectedFlowStatus: [],
  flowStatusRange: function () {
    return this.selectedFlowStatus.length ? this.selectedFlowStatus : null;
  },
});

const isLoading = ref(false);
const queriedResult = ref([]);

const handleCustomQuery = () => {
  let range = queryConditions.value.timeRange();
  isLoading.value = true;
  handleQuery(range.from, range.to)
    .then((data) => {
      queriedResult.value = data;
    })
    .catch((error) => {})
    .finally(() => {
      isLoading.value = false;
    });
};

const currentResult = computed(
  () => journalStore.diversionShareStatus.currentList
);

const tableData = computed(() => {
  let data =
    queryConditions.value.rangeType == "current"
      ? currentResult.value
      : queriedResult.value;
  let airportRange = queryConditions.value.airportRange();
  let intentionRange = queryConditions.value.intentionRange();
  let planStatusRange = queryConditions.value.planStatusRange();
  let flowStatusRange = queryConditions.value.flowStatusRange();
  if (airportRange) {
    data = data.filter((item) => airportRange.includes(item.diversionAirport));
  }
  if (intentionRange) {
    data = data.filter((item) => intentionRange.includes(item.intentionRange));
  }
  if (planStatusRange) {
    data = data.filter((item) =>
      planStatusRange.includes(item.planStatusRange)
    );
  }
  if (flowStatusRange) {
    data = data.filter((item) => airportRange.includes(item.flowStatusRange));
  }
  data = data.filter((item) => item.setDisposed == 0);
  return data;
});

const updateItem = (item, key, value) => {
  const target = JSON.parse(JSON.stringify(item));
  target[key] = value;
  target[key + "SeatIP"] = seatStore.currentSeat.ip;
  target[key + "SeatName"] = seatStore.currentSeat.seatName;
  target[key + "SeatUser"] = seatStore.currentSeatData
    ? seatStore.currentSeatData.users.map((u) => u.userName).join(", ")
    : "未知";
  target[key + "Time"] = new Date();
  // 直接替store中的换现有项目
  if (queryConditions.value.rangeType == "current") {
    for (
      let i = 0;
      i < journalStore.diversionShareStatus.currentList.length;
      i++
    ) {
      if (
        journalStore.diversionShareStatus.currentList[i].number == target.number
      ) {
        journalStore.diversionShareStatus.currentList[i] = target;
      }
    }
  } else {
    for (let i = 0; i < queriedResult.value.length; i++) {
      if (queriedResult.value[i].number == target.number) {
        queriedResult.value[i] = target;
        break;
      }
    }
  }
  handleSave(target);
};
</script>

<style lang="css" scoped>
.cmdbar-container {
  width: 100%;
  padding: 12px 16px;
}

.cmdbar-item-container {
  display: flex;
  align-items: center;
}

.cmdbar-item-container > *:not(:last-child) {
  margin-right: 8px !important;
}

.table-container {
  width: 100%;
  max-width: 100%;
}

.title-container {
  width: 100%;
  padding: 16px;
  display: flex;
  align-items: center;
  font-size: 24px;
  font-weight: bolder;
  color: var(--el-text-color-regular);
}

.vertical-align-center {
  display: flex;
  align-items: center;
}

.row-opreator-container {
  width: 100%;
  padding: 8px;
}

.row-opreator-details {
  width: 100%;
  display: flex;
  align-items: center;
  padding: 4px 8px;
}

.row-opreator-details > *:not(:last-child) {
  margin-right: 24px;
}
</style>
